package com.example.finalwork.controller;

import com.example.finalwork.entity.User;
import com.example.finalwork.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/")
public class AuthController {

    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        Map<String, Object> response = new HashMap<>();
        Optional<User> userOptional = userService.login(username, password);

        if (userOptional.isPresent()) {
            response.put("success", true);
            response.put("message", "登录成功！");
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误！");
        }
        return response;
    }

    @PostMapping("/login/reset-password")
    public Map<String, Object> resetPassword(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String newPassword = params.get("newPassword");

        boolean success = userService.resetPassword(username, newPassword);
        Map<String, Object> response = new HashMap<>();

        if (success) {
            response.put("success", true);
            response.put("message", "密码重置成功！");
        } else {
            response.put("success", false);
            response.put("message", "重置密码失败，请检查用户名。");
        }
        return response;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> userParams) {
        String username = userParams.get("username");
        String password = userParams.get("password");
        String email = userParams.get("email");
        String phone = userParams.get("phone");
        String gender = userParams.get("gender");
        String dob = userParams.get("dob");

        boolean success = userService.registerUser(username, password, email, phone, gender, dob);
        Map<String, Object> response = new HashMap<>();

        if (success) {
            response.put("success", true);
            response.put("message", "注册成功！");
        } else {
            response.put("success", false);
            response.put("message", "注册失败，用户名可能已存在！");
        }
        return response;
    }
}
